﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autofac;

namespace BasicCMS
{
    public class ObjectContainer
    {
        private static IContainer _container;

        public static void SetContainer(IContainer container)
        {
            _container = container;
        }

        /// <summary>
        /// 解析对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T ResolveService<T>()
        {
            if (_container == null)
                return default(T);

            return _container.Resolve<T>();
        }

        public static T ResolveService<T>(IDictionary<string, object> parameters)
        {
            if (_container == null)
                return default(T);

            var args = parameters.Select(m => new NamedParameter(m.Key, m.Value)).ToArray();

            return _container.Resolve<T>(args);
        }

        /// <summary>
        /// 解析对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T ResolveNamed<T>(string name)
        {
            if (_container == null)
                return default(T);

            return _container.ResolveNamed<T>(name);
        }

        /// <summary>
        /// 根据对象类型解析对象
        /// </summary>
        /// <param name="instanceType"></param>
        /// <returns></returns>
        public static object ResolveService(Type instanceType)
        {
            if (_container == null)
                return null;

            return _container.Resolve(instanceType);
        }

        /// <summary>
        /// 解析对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IEnumerable<T> ResolveServices<T>()
        {
            return ResolveService<IEnumerable<T>>();
        }
    }
}
